package com.ruoyi.worker.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Joiner;
import com.google.common.collect.Maps;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.RedisNoUtil;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.worker.domain.*;
import com.ruoyi.worker.mapper.OperationNeedMapper;
import com.ruoyi.worker.service.OperationNeedService;
import org.apache.commons.compress.utils.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @ProjectName: ruoyi
 * @Package: com.ruoyi.system.service.impl
 * @ClassName: OperationNeedServiceImpl
 * @Author: 胡志明
 * @Description: OperationNeedService
 * @Date: 2021/9/9 21:28
 */
@Service
public class OperationNeedServiceImpl implements OperationNeedService {

    @Autowired
    private OperationNeedMapper operationNeedMapper;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public List<QualityPredictPojo> getQualityPredictList(QualityPredictPojo qualityPredictPojo) {
        List<QualityPredictPojo> qualityPredictPojoList = operationNeedMapper.getQualityPredictList(qualityPredictPojo);
        return qualityPredictPojoList;
    }

    @Override
    public QualityPredictPojo viewUserData(Integer userId) {
        QualityPredictPojo qualityPredictPojo = operationNeedMapper.viewUserData(userId);
        String yzoyw = RedisNoUtil.getAddNo("YZOZL", redisTemplate);
        qualityPredictPojo.setDocumentNumber(yzoyw);
        return qualityPredictPojo;
    }

    @Override
    public List<Map<String, Object>> viewTimeShift() {
        //List<Map<String, Object>> list = operationNeedMapper.viewTimeShift();
        List<Map<String, Object>> list = operationNeedMapper.termTimeShif();
        return list;
    }

    @Override
    public List<OperationNeedPojo> getOperationNeedList(OperationNeedPojo operationNeedPojo) {
        List<OperationNeedPojo> operationNeedList = operationNeedMapper.getOperationNeedList(operationNeedPojo.getNeedTime());
        return operationNeedList;
    }

    @Override
    public JSONArray addShowOperationNeed() {
        JSONArray jsonArray = new JSONArray();
        List<String> timeShiftNameList = operationNeedMapper.getTimeShiftName();
        List<Map<String, Object>> sysPostNameList = operationNeedMapper.getSysPostName();
        for (int i = 0; i < timeShiftNameList.size(); i++) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("timeShiftName", timeShiftNameList.get(i));
            jsonObject.put("sysPostNames", sysPostNameList);
            jsonArray.add(jsonObject);
        }
        return jsonArray;
    }

    @Override
    @Transactional
    public int addOperationNeed(JSONObject jsonObject) {
        List<OperationNeedDetailPojo> addOperationNeedDetailList = new ArrayList<>();
        List<OperationNeedDetailPojo> operationNeedDetailList = new ArrayList<>();
        //String taskNumber = jsonObject.get("taskNumber")+"";
        String needTime = jsonObject.get("needTime") + "";
        String seqNo = RedisNoUtil.getSeqNo(needTime, redisTemplate);
//        Integer checkTaskNumber = operationNeedMapper.checkTaskNumber(needTime+seqNo);
//        if (checkTaskNumber > 0){
//            return 1;
//        }
//        Integer checkNeedTime = operationNeedMapper.checkNeedTime(needTime);
//        if (checkNeedTime > 0){
//            return 2;
//        }
        String remark = jsonObject.get("remark") + "";
        JSONArray operationNeedList = jsonObject.getJSONArray("operationNeedList");
        int manSumNumber = 0;
        int womanSumNumber = 0;
        for (int i = 0; i < operationNeedList.size(); i++) {
            JSONObject detail = operationNeedList.getJSONObject(i);
            String timeShiftName = detail.get("timeShiftName") + "";
            JSONArray sysPostNames = detail.getJSONArray("sysPostNames");
            for (int j = 0; j < sysPostNames.size(); j++) {
                OperationNeedDetailPojo operationNeedDetailPojo = new OperationNeedDetailPojo();
                JSONObject json = sysPostNames.getJSONObject(j);
                String postName = json.get("postName") + "";
                Integer manNumber = json.getInteger("manNumber");
                Integer womanNumber = json.getInteger("womanNumber");
                operationNeedDetailPojo.setPostName(postName);
                operationNeedDetailPojo.setTimeShiftName(timeShiftName);
                operationNeedDetailPojo.setManNumber(manNumber);
                operationNeedDetailPojo.setWomanNumber(womanNumber);
                operationNeedDetailList.add(operationNeedDetailPojo);
                manSumNumber += manNumber;
                womanSumNumber += womanNumber;
            }
        }
        OperateNeedVaryPojo operateNeedVaryPojo = new OperateNeedVaryPojo();
        operateNeedVaryPojo.setTaskNumber(needTime + seqNo);
        operateNeedVaryPojo.setNeedTime(needTime);
        operateNeedVaryPojo.setRemark(remark);
        operateNeedVaryPojo.setManSumNumber(manSumNumber);
        operateNeedVaryPojo.setWomanSumNumber(womanSumNumber);
        operateNeedVaryPojo.setSumNumber(manSumNumber + womanSumNumber);
        operationNeedMapper.addOperateNeed(operateNeedVaryPojo);

        for (int i = 0; i < operationNeedDetailList.size(); i++) {
            OperationNeedDetailPojo operationNeedDetailPojo = operationNeedDetailList.get(i);
            operationNeedDetailPojo.setOperationNeedId(operateNeedVaryPojo.getOperationNeedId());
            addOperationNeedDetailList.add(operationNeedDetailPojo);
        }

        if (addOperationNeedDetailList.size() > 0) {
            operationNeedMapper.addOperationNeedDetailByList(addOperationNeedDetailList);
        }

        SysUser user = SecurityUtils.getLoginUser().getUser();
        TaskChangePojo taskChangePojo = new TaskChangePojo();
        taskChangePojo.setTaskId(operateNeedVaryPojo.getOperationNeedId());
        taskChangePojo.setChangeUserId(user.getUserId().intValue());
        taskChangePojo.setChangeUserName(user.getUserName());
        taskChangePojo.setChangData(user.getUserName() + " " + "新增用工需求");
        operationNeedMapper.addTaskChangePojo(taskChangePojo);
        return 0;
    }

    @Override
    public void deleteOperationNeed(Integer operationNeedId) {
        operationNeedMapper.deleteOperationNeed(operationNeedId);
        operationNeedMapper.deleteOperationNeedDetail(operationNeedId);
        operationNeedMapper.deleteStaffAssignmentsByOId(operationNeedId);
    }

//    public static void main(String[] args) {
//        System.out.println(15.0/32.0*100);
//        System.out.println(Math.floor(15.0/32.0*100));
//        double floor = Math.floor(15.0 / 32.0 * 100);
//        int a = (int) floor;
//        System.out.println(a);
//    }

    @Override
    @Transactional
    public void auditOperationNeed(OperateNeedVaryPojo operateNeedVaryPojo) {
        Integer operationNeedId = operateNeedVaryPojo.getOperationNeedId();
        Integer taskNode = operateNeedVaryPojo.getTaskNode();
        operationNeedMapper.auditOperationNeed(operateNeedVaryPojo);
        SysUser user = SecurityUtils.getLoginUser().getUser();
        TaskChangePojo taskChangePojo = new TaskChangePojo();
        taskChangePojo.setTaskId(operationNeedId);
        taskChangePojo.setChangeUserId(user.getUserId().intValue());
        taskChangePojo.setChangeUserName(user.getUserName());
        if (taskNode == 1) {//审核通过
            taskChangePojo.setChangData(user.getUserName() + " " + "审核通过");
            List<CreateStaffAssignmentsPojo> firmOperateNeedDetailList = operationNeedMapper.getStaffAssignmentsByOId(operationNeedId);
            if (firmOperateNeedDetailList.size() > 0) {
                CreateStaffAssignmentsPojo createStaffAssignmentsPojoOne = firmOperateNeedDetailList.get(0);
                StaffAssignmentsPojo staffAssignmentsPojo = new StaffAssignmentsPojo();
                staffAssignmentsPojo.setOperationNeedId(createStaffAssignmentsPojoOne.getOperationNeedId());
                staffAssignmentsPojo.setNeedTime(createStaffAssignmentsPojoOne.getNeedTime());
                staffAssignmentsPojo.setTaskNode(0);
                staffAssignmentsPojo.setTaskNumber(createStaffAssignmentsPojoOne.getTaskNumber());
                double manSumNumber = createStaffAssignmentsPojoOne.getManSumNumber();
                double womanSumNumber = createStaffAssignmentsPojoOne.getWomanSumNumber();
                int manfloor = (int)Math.floor(manSumNumber / (manSumNumber + womanSumNumber) * 100);
                int womanfloor = (int)Math.floor(womanSumNumber / (manSumNumber + womanSumNumber) * 100);

                staffAssignmentsPojo.setManNumberScale(manfloor);
                staffAssignmentsPojo.setWomanNumberScale(womanfloor);
                operationNeedMapper.addStaffAssignments(staffAssignmentsPojo);
                Map<String, Map<String, Integer>> timeShiftMap = new HashMap<>();
                for (int i = 0; i < firmOperateNeedDetailList.size(); i++) {
                    CreateStaffAssignmentsPojo createStaffAssignmentsPojo = firmOperateNeedDetailList.get(i);
                    String timeShiftName = createStaffAssignmentsPojo.getTimeShiftName();
                    Integer manNumber = createStaffAssignmentsPojo.getManNumber();
                    Integer womanNumber = createStaffAssignmentsPojo.getWomanNumber();
                    if (timeShiftMap.containsKey(timeShiftName)) {
                        Map<String, Integer> stringIntegerMap = timeShiftMap.get(timeShiftName);
                        stringIntegerMap.put("man", stringIntegerMap.get("man") + manNumber);
                        stringIntegerMap.put("woman", stringIntegerMap.get("woman") + womanNumber);
                        timeShiftMap.put(timeShiftName, stringIntegerMap);
                    } else {
                        Map<String, Integer> stringIntegerMap = new HashMap<>();
                        stringIntegerMap.put("man", manNumber);
                        stringIntegerMap.put("woman", womanNumber);
                        timeShiftMap.put(timeShiftName, stringIntegerMap);
                    }
                }
                List<Map<String, Object>> timeShiftTypeMapList = operationNeedMapper.getTimeShiftType();
                List<Map<String, Object>> companyMapList = operationNeedMapper.getCompanyData();
                List<StaffAssignmentsDetailPojo> addStaffAssignmentsDetailPojo = new ArrayList<>();
                for (int i = 0; i < timeShiftTypeMapList.size(); i++) {
                    Map<String, Object> map = timeShiftTypeMapList.get(i);
                    String timeShiftName = map.get("name") + "";
                    Integer timeShiftType = Integer.parseInt(map.get("type") + "");
                    Map<String, Integer> stringIntegerMap = timeShiftMap.get(timeShiftName);
                    Integer man = stringIntegerMap.get("man");//当前班次实际男性用人总数
                    Integer woman = stringIntegerMap.get("woman");//当前实际女性用人总数
                    Map<String, StaffAssignmentsDetailPojo> maxScale = new HashMap<>();
                    int realMmanNumber = 0;//实际男性用人数
                    int realWomanNumber = 0;//实际女性用人数
                    int maxScaleInt = 0;//最大分配比例
                    for (int j = 0; j < companyMapList.size(); j++) {
                        StaffAssignmentsDetailPojo staffAssignmentsDetailPojo = new StaffAssignmentsDetailPojo();
                        staffAssignmentsDetailPojo.setStaffAssignmentsId(staffAssignmentsPojo.getStaffAssignmentsId());
                        staffAssignmentsDetailPojo.setTimeShiftName(timeShiftName);
                        staffAssignmentsDetailPojo.setType(timeShiftType);
                        Map<String, Object> companyMap = companyMapList.get(j);
                        Integer companyId = Integer.parseInt(companyMap.get("id") + "");
                        String company = companyMap.get("company") + "";
                        String rStr = companyMap.get("recruitPercent") + "";
                        if ("".equals(rStr) || "null".equals(rStr)) {
                            rStr = "0";
                        }
                        double recruitPercent = Double.parseDouble(rStr);
                        double manNumberfloor = Math.floor(man * recruitPercent / 100);
                        double womanNumberfloor = Math.floor(woman * recruitPercent / 100);
                        int manNumber = (int) manNumberfloor;
                        int womanNumber = (int) womanNumberfloor;
                        realMmanNumber += manNumber;
                        realWomanNumber += womanNumberfloor;
                        int scale = (int) recruitPercent;
                        staffAssignmentsDetailPojo.setCompanyId(companyId);
                        staffAssignmentsDetailPojo.setCompanyName(company);
//                        staffAssignmentsDetailPojo.setManScale(scale);
//                        staffAssignmentsDetailPojo.setWomanScale(scale);
                        staffAssignmentsDetailPojo.setManNumber(manNumber);
                        staffAssignmentsDetailPojo.setWomanNumber(womanNumber);
                        if (scale > maxScaleInt) {//当前比例大则替换
                            maxScaleInt = scale;
                            StaffAssignmentsDetailPojo staffAssignmentsDetailPojo1 = maxScale.get("saPojo");
                            addStaffAssignmentsDetailPojo.add(staffAssignmentsDetailPojo1);
                            maxScale.put("saPojo", staffAssignmentsDetailPojo);
                        } else {
                            addStaffAssignmentsDetailPojo.add(staffAssignmentsDetailPojo);
                        }
                    }
                    if (man > realMmanNumber) {
                        StaffAssignmentsDetailPojo staffAssignmentsDetailPojo = maxScale.get("saPojo");
                        Integer manNumber = staffAssignmentsDetailPojo.getManNumber();
                        staffAssignmentsDetailPojo.setManNumber(manNumber + (man - realMmanNumber));
                    }
                    if (woman > realWomanNumber) {
                        StaffAssignmentsDetailPojo staffAssignmentsDetailPojo = maxScale.get("saPojo");
                        Integer womanNumber = staffAssignmentsDetailPojo.getWomanNumber();
                        staffAssignmentsDetailPojo.setWomanNumber(womanNumber + (woman - realWomanNumber));
                    }
                    addStaffAssignmentsDetailPojo.add(maxScale.get("saPojo"));
                }
                if (addStaffAssignmentsDetailPojo.size() > 0) {
                    operationNeedMapper.addStaffAssignmentsDetailPojo(addStaffAssignmentsDetailPojo);
                }
            }
        } else {
            taskChangePojo.setChangData(user.getUserName() + " " + "审核驳回");
        }
        operationNeedMapper.addTaskChangePojo(taskChangePojo);
    }

    @Override
    @Transactional
    public void updateOperationNeed(JSONObject jsonObject) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        String taskNumber = jsonObject.get("taskNumber") + "";
        String needTime = jsonObject.get("needTime") + "";
        String remark = jsonObject.get("remark") + "";
        Integer operationNeedId = jsonObject.getInteger("operationNeedId");
        operationNeedMapper.deleteOperationNeedDetail(operationNeedId);
        JSONArray operationNeedList = jsonObject.getJSONArray("operationNeedList");
        JSONArray firstOperationNeedList = jsonObject.getJSONArray("firstOperationNeedList");
        Map<String, Integer> sumNumberMap = new HashMap<>();
        List<TaskChangePojo> taskChangePojos = new ArrayList<>();
        for (int i = 0; i < firstOperationNeedList.size(); i++) {
            JSONObject jsonObject1 = firstOperationNeedList.getJSONObject(i);
            String timeShiftName = jsonObject1.get("timeShiftName") + "";
            JSONArray sysPostNames = jsonObject1.getJSONArray("timeShiftValue");
            for (int j = 0; j < sysPostNames.size(); j++) {
                JSONObject json = sysPostNames.getJSONObject(j);
                String postName = json.get("postName") + "";
                Integer manNumber = json.getInteger("manNumber");
                Integer womanNumber = json.getInteger("womanNumber");
                String key = timeShiftName + postName + "man";
                sumNumberMap.put(key, manNumber);
                key = timeShiftName + postName + "woman";
                sumNumberMap.put(key, womanNumber);
            }
        }
        List<OperationNeedDetailPojo> addOperationNeedDetailList = new ArrayList<>();
        int manSumNumber = 0;
        int womanSumNumber = 0;
        for (int i = 0; i < operationNeedList.size(); i++) {
            JSONObject detail = operationNeedList.getJSONObject(i);
            String timeShiftName = detail.get("timeShiftName") + "";
            JSONArray sysPostNames = detail.getJSONArray("timeShiftValue");
            for (int j = 0; j < sysPostNames.size(); j++) {
                OperationNeedDetailPojo operationNeedDetailPojo = new OperationNeedDetailPojo();
                JSONObject json = sysPostNames.getJSONObject(j);
                String postName = json.get("postName") + "";
                Integer manNumber = json.getInteger("manNumber");
                String key = timeShiftName + postName + "man";
                Integer integer = sumNumberMap.get(key);
                if (integer != manNumber) {
                    TaskChangePojo taskChangePojo = new TaskChangePojo();
                    taskChangePojo.setTaskId(operationNeedId);
                    taskChangePojo.setChangeUserId(user.getUserId().intValue());
                    taskChangePojo.setChangeUserName(user.getUserName());
                    taskChangePojo.setChangData(user.getUserName() + " " + timeShiftName + "-" + postName + "-男性，由" + integer + "改为" + manNumber);
                    taskChangePojos.add(taskChangePojo);
                }
                Integer womanNumber = json.getInteger("womanNumber");
                key = timeShiftName + postName + "woman";
                Integer integer1 = sumNumberMap.get(key);
                if (integer1 != womanNumber) {
                    TaskChangePojo taskChangePojo = new TaskChangePojo();
                    taskChangePojo.setTaskId(operationNeedId);
                    taskChangePojo.setChangeUserId(user.getUserId().intValue());
                    taskChangePojo.setChangeUserName(user.getUserName());
                    taskChangePojo.setChangData(user.getUserName() + " " + timeShiftName + "-" + postName + "-女性，由" + integer1 + "改为" + womanNumber);
                    taskChangePojos.add(taskChangePojo);
                }
                operationNeedDetailPojo.setPostName(postName);
                operationNeedDetailPojo.setTimeShiftName(timeShiftName);
                operationNeedDetailPojo.setManNumber(manNumber);
                operationNeedDetailPojo.setWomanNumber(womanNumber);
                operationNeedDetailPojo.setOperationNeedId(operationNeedId);
                addOperationNeedDetailList.add(operationNeedDetailPojo);
                manSumNumber += manNumber;
                womanSumNumber += womanNumber;
            }
        }
        OperateNeedVaryPojo operateNeedVaryPojo = new OperateNeedVaryPojo();
        operateNeedVaryPojo.setOperationNeedId(operationNeedId);
        operateNeedVaryPojo.setManSumNumber(manSumNumber);
        operateNeedVaryPojo.setWomanSumNumber(womanSumNumber);
        operateNeedVaryPojo.setSumNumber(manSumNumber + womanSumNumber);
        operateNeedVaryPojo.setRemark(remark);
        operationNeedMapper.updateOperationNeedById(operateNeedVaryPojo);
        if (addOperationNeedDetailList.size() > 0) {
            operationNeedMapper.addOperationNeedDetailByList(addOperationNeedDetailList);
        }
        if (taskChangePojos.size() > 0) {
            for (int i = 0; i < taskChangePojos.size(); i++) {
                operationNeedMapper.addTaskChangePojo(taskChangePojos.get(i));
            }
        }
    }

    @Override
    public JSONObject viewOperationNeed(Integer operationNeedId) {
        JSONObject jsonObject = new JSONObject();
        List<FirmOperateNeedDetail> firmOperateNeedDetailList = operationNeedMapper.getFirmOperateNeedDetail(operationNeedId);
        List<TaskChangePojo> taskChangePojos = operationNeedMapper.getTaskChangePojoByOId(operationNeedId);
        if (firmOperateNeedDetailList.size() > 0) {
            Map<String, JSONArray> map = new HashMap<>();
            FirmOperateNeedDetail firmOperateNeedDetailOne = firmOperateNeedDetailList.get(0);
            String needTime = firmOperateNeedDetailOne.getNeedTime();
            String taskNumber = firmOperateNeedDetailOne.getTaskNumber();
            String remark = firmOperateNeedDetailOne.getRemark();
            jsonObject.put("needTime", needTime);
            jsonObject.put("taskNumber", taskNumber);
            jsonObject.put("remark", remark);
            jsonObject.put("taskChangePojos", taskChangePojos);
            for (int i = 0; i < firmOperateNeedDetailList.size(); i++) {
                FirmOperateNeedDetail firmOperateNeedDetail = firmOperateNeedDetailList.get(i);
                String timeShiftName = firmOperateNeedDetail.getTimeShiftName();
                if (map.containsKey(timeShiftName)) {
                    JSONArray objects = map.get(timeShiftName);
                    JSONObject object = new JSONObject();
                    object.put("postName", firmOperateNeedDetail.getPostName());
                    object.put("manNumber", firmOperateNeedDetail.getManNumber());
                    object.put("womanNumber", firmOperateNeedDetail.getWomanNumber());
                    objects.add(object);
                    map.put(timeShiftName, objects);
                } else {
                    JSONArray objects = new JSONArray();
                    JSONObject object = new JSONObject();
                    object.put("postName", firmOperateNeedDetail.getPostName());
                    object.put("manNumber", firmOperateNeedDetail.getManNumber());
                    object.put("womanNumber", firmOperateNeedDetail.getWomanNumber());
                    objects.add(object);
                    map.put(timeShiftName, objects);
                }
            }
            JSONArray mapJsonArray = new JSONArray();
            for (Map.Entry<String, JSONArray> m : map.entrySet()) {
                JSONObject mapJsonObject = new JSONObject();
                mapJsonObject.put("timeShiftName", m.getKey());
                mapJsonObject.put("timeShiftValue", m.getValue());
                mapJsonArray.add(mapJsonObject);
            }
            jsonObject.put("timeShiftData", mapJsonArray);
        }
        return jsonObject;
    }

    @Override
    public List<StaffAssignmentsPojo> getStaffAssignmentsList(String needTime) {
        List<StaffAssignmentsPojo> staffAssignmentsList = operationNeedMapper.getStaffAssignmentsList(needTime);
        return staffAssignmentsList;
    }

    @Override
    @Transactional
    public void auditStaffAssignments(StaffAssignmentsPojo staffAssignmentsPojo) throws Exception {
        String checkRemark = staffAssignmentsPojo.getCheckRemark();
        Integer taskNode = staffAssignmentsPojo.getTaskNode();
        Integer staffAssignmentsId = staffAssignmentsPojo.getStaffAssignmentsId();
        SysUser user = SecurityUtils.getLoginUser().getUser();
        TaskChangePojo taskChangePojo = new TaskChangePojo();
        taskChangePojo.setTaskId(staffAssignmentsId);
        taskChangePojo.setChangeUserId(user.getUserId().intValue());
        taskChangePojo.setChangeUserName(user.getUserName());
        if (taskNode == 1) {//审核通过
            operationNeedMapper.updateStaffAssignments(staffAssignmentsId, 3, checkRemark);
            String operationNeedId = operationNeedMapper.getOperationNeedId(staffAssignmentsId);
            if (!"".equals(operationNeedId) && operationNeedId != null) {
                staffAssignmentsPojo.setTaskNode(3);
                this.setRedisCache(staffAssignmentsPojo);
                EmploymentPlanStatistics employmentPlanStatistics = operationNeedMapper.getEmploymentPlanStatisticsBySId(staffAssignmentsId);
                employmentPlanStatistics.setCreateBy(user.getUserName());
                operationNeedMapper.addEmploymentPlanStatistics(employmentPlanStatistics);
            }
            if(null ==checkRemark || "".equals(checkRemark)){
                taskChangePojo.setChangData(user.getUserName() + " " + "审核通过");
            }else{
                taskChangePojo.setChangData(user.getUserName() + " " + "审核通过,备注："+checkRemark);
            }

        } else if (taskNode == 2) {//审核不通过
            operationNeedMapper.updateStaffAssignments(staffAssignmentsId, 2, checkRemark);
            if(null ==checkRemark || "".equals(checkRemark)){
                taskChangePojo.setChangData(user.getUserName() + " " + "审核驳回");
            }else{
                taskChangePojo.setChangData(user.getUserName() + " " + "审核驳回,备注："+checkRemark);
            }

        }
        operationNeedMapper.addTaskChangePojo(taskChangePojo);
    }

    /**
     * @param staffAssignmentsPojo
     * @return void
     * @Description : 设置渠道商需求缓存数据
     * @Author : leizhang
     * @Date 10:54 上午 2021/9/12
     **/
    public void setRedisCache(StaffAssignmentsPojo staffAssignmentsPojo) throws Exception {
        final Joiner JOINER = Joiner.on("_").skipNulls();
        List<StaffAssignmentsPojo> assignmentsInfo = operationNeedMapper.getAssignmentsInfo(staffAssignmentsPojo);
        //拼接key
        StaffAssignmentsPojo staffAssignmentsPojo1 = assignmentsInfo.get(0);
        List<List<StaffAssignmentsDetailPojo>> companyOfList = Lists.newArrayList();
        staffAssignmentsPojo1.getDetailPojoList().stream().collect(Collectors.groupingBy(StaffAssignmentsDetailPojo::getCompanyId, Collectors.toList()))
                .forEach((companyId, companyList) -> {
                    companyOfList.add(companyList);
                });
        String needTime = staffAssignmentsPojo1.getNeedTime();
        Map<String, Object> valueMap = null;
        Map<String, Map<String, Object>> redisMap = Maps.newHashMap();
        for (List<StaffAssignmentsDetailPojo> staffAssignmentsDetailPojos : companyOfList) {
            for (StaffAssignmentsDetailPojo staffAssignmentsDetailPojo : staffAssignmentsDetailPojos) {
                String redisKey = JOINER.join(staffAssignmentsDetailPojo.getCompanyId(), StringUtils.deleteString(needTime, '-'));
                if (null == redisMap.get(redisKey) || redisMap.get(redisKey).isEmpty()) {
                    valueMap = Maps.newHashMap();
                    valueMap.put(JOINER.join(staffAssignmentsDetailPojo.getType(), 1), staffAssignmentsDetailPojo.getManNumber());
                    valueMap.put(JOINER.join(staffAssignmentsDetailPojo.getType(), 2), staffAssignmentsDetailPojo.getWomanNumber());
                    redisMap.put(redisKey, valueMap);
                } else {
                    valueMap = redisMap.get(redisKey);
                    valueMap.put(JOINER.join(staffAssignmentsDetailPojo.getType(), 1), staffAssignmentsDetailPojo.getManNumber());
                    valueMap.put(JOINER.join(staffAssignmentsDetailPojo.getType(), 2), staffAssignmentsDetailPojo.getWomanNumber());
                    redisMap.put(redisKey, valueMap);
                }
            }
        }
        for (Map.Entry<String, Map<String, Object>> stringMapEntry : redisMap.entrySet()) {
            redisCache.setCacheMap(stringMapEntry.getKey(), stringMapEntry.getValue(), DateUtils.getOverTime_24(needTime));
        }
    }


    @Override
    public void deleteStaffAssignments(Integer staffAssignmentsId) {
        operationNeedMapper.deleteStaffAssignments(staffAssignmentsId);
        operationNeedMapper.detStaffAssignmentsDetail(staffAssignmentsId);
    }

    @Override
    public JSONObject viewStaffAssignments(Integer staffAssignmentsId) {
        JSONObject jsonObject = new JSONObject();
        List<StaffAssignmentsVaryPojo> staffAssignmentsVaryPojoList = operationNeedMapper.getStaffAssignmentsDetail(staffAssignmentsId);
        List<TaskChangePojo> taskChangePojos = operationNeedMapper.getTaskChangePojoByOId(staffAssignmentsId);
        if (staffAssignmentsVaryPojoList.size() > 0) {
            Map<String, JSONArray> map = new HashMap<>();
            Map<String, Map<String, Integer>> numberMap = new HashMap<>();
            StaffAssignmentsVaryPojo staffAssignmentsVaryPojo = staffAssignmentsVaryPojoList.get(0);
            String needTime = staffAssignmentsVaryPojo.getNeedTime();
            String taskNumber = staffAssignmentsVaryPojo.getTaskNumber();
            int manNumberScale = (int)staffAssignmentsVaryPojo.getManNumberScale();
            int womanNumberScale = (int)staffAssignmentsVaryPojo.getWomanNumberScale();
            Integer personnelOddNumber = staffAssignmentsVaryPojo.getPersonnelOddNumber();
            jsonObject.put("needTime", needTime);
            jsonObject.put("taskNumber", taskNumber);
            jsonObject.put("manNumberScale", manNumberScale);
            jsonObject.put("womanNumberScale", womanNumberScale);
            jsonObject.put("taskChangePojos", taskChangePojos);
            jsonObject.put("personnelOddNumber", personnelOddNumber);
            for (int i = 0; i < staffAssignmentsVaryPojoList.size(); i++) {
                StaffAssignmentsVaryPojo staffAssignmentsVaryPojo1 = staffAssignmentsVaryPojoList.get(i);
                String timeShiftName = staffAssignmentsVaryPojo1.getTimeShiftName();
                if (map.containsKey(timeShiftName)) {
                    JSONArray objects = map.get(timeShiftName);
                    JSONObject object = new JSONObject();
                    object.put("companyName", staffAssignmentsVaryPojo1.getCompanyName());
                    object.put("companyId", staffAssignmentsVaryPojo1.getCompanyId());
                    object.put("manScale", staffAssignmentsVaryPojo1.getManScale());
                    object.put("manNumber", staffAssignmentsVaryPojo1.getManNumber());
                    object.put("womanNumber", staffAssignmentsVaryPojo1.getWomanNumber());
                    object.put("type", staffAssignmentsVaryPojo1.getType());
                    objects.add(object);
                    map.put(timeShiftName, objects);

                    Map<String, Integer> stringIntegerMap = numberMap.get(timeShiftName);
                    stringIntegerMap.put("man", stringIntegerMap.get("man") + staffAssignmentsVaryPojo1.getManNumber());
                    stringIntegerMap.put("woman", stringIntegerMap.get("woman") + staffAssignmentsVaryPojo1.getWomanNumber());
                    numberMap.put(timeShiftName, stringIntegerMap);
                } else {
                    JSONArray objects = new JSONArray();
                    JSONObject object = new JSONObject();
                    object.put("companyName", staffAssignmentsVaryPojo1.getCompanyName());
                    object.put("companyId", staffAssignmentsVaryPojo1.getCompanyId());
                    object.put("manScale", staffAssignmentsVaryPojo1.getManScale());
                    object.put("manNumber", staffAssignmentsVaryPojo1.getManNumber());
                    object.put("womanNumber", staffAssignmentsVaryPojo1.getWomanNumber());
                    object.put("type", staffAssignmentsVaryPojo1.getType());
                    objects.add(object);
                    map.put(timeShiftName, objects);

                    Map<String, Integer> stringIntegerMap = new HashMap<>();
                    stringIntegerMap.put("man", staffAssignmentsVaryPojo1.getManNumber());
                    stringIntegerMap.put("woman", staffAssignmentsVaryPojo1.getWomanNumber());
                    numberMap.put(timeShiftName, stringIntegerMap);
                }
            }
            JSONArray mapJsonArray = new JSONArray();
            for (Map.Entry<String, JSONArray> m : map.entrySet()) {
                JSONObject mapJsonObject = new JSONObject();
                Map<String, Integer> stringIntegerMap = numberMap.get(m.getKey());
                Integer man = stringIntegerMap.get("man");
                Integer woman = stringIntegerMap.get("woman");
                String key = m.getKey();
                mapJsonObject.put("tsName", key);
                mapJsonObject.put("totalNum", man + woman);
                mapJsonObject.put("timeShiftName", key + " " + "男性需求人数：" + man + "人 " + "女性需求人数：" + woman + "人");
                mapJsonObject.put("timeShiftValue", m.getValue());
                mapJsonArray.add(mapJsonObject);
            }
            jsonObject.put("timeShiftData", mapJsonArray);
            jsonObject.put("numberMap", numberMap);
        }
        return jsonObject;
    }

    @Override
    @Transactional
    public void updateStaffAssignments(JSONObject jsonObject) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        Integer staffAssignmentsId = jsonObject.getInteger("staffAssignmentsId");

        JSONArray operationNeedList = jsonObject.getJSONArray("operationNeedList");
        JSONArray firstOperationNeedList = jsonObject.getJSONArray("firstOperationNeedList");
        Map<String, Integer> sumNumberMap = new HashMap<>();
        List<TaskChangePojo> taskChangePojos = new ArrayList<>();
        int totalManNum =0;
        int totalwoManNum =0;
        for (int i = 0; i < firstOperationNeedList.size(); i++) {
            JSONObject jsonObject1 = firstOperationNeedList.getJSONObject(i);
            //String timeShiftName = jsonObject1.get("timeShiftName")+"";
            String timeShiftName = jsonObject1.get("tsName") + "";
            JSONArray sysPostNames = jsonObject1.getJSONArray("timeShiftValue");
            for (int j = 0; j < sysPostNames.size(); j++) {
                JSONObject json = sysPostNames.getJSONObject(j);
                String companyName = json.get("companyName") + "";
                Integer manScale = json.getInteger("manScale");
                Integer manNumber = json.getInteger("manNumber");
                Integer womanNumber = json.getInteger("womanNumber");

                String key = timeShiftName + companyName + "man";
                sumNumberMap.put(key, manNumber);
                key = timeShiftName + companyName + "woman";
                sumNumberMap.put(key, womanNumber);
                key = timeShiftName + companyName + "scale";
                sumNumberMap.put(key, manScale);
            }
        }

        List<StaffAssignmentsDetailPojo> addStaffAssignmentsDetailPojo = new ArrayList<>();
        for (int i = 0; i < operationNeedList.size(); i++) {
            JSONObject detail = operationNeedList.getJSONObject(i);
            //String timeShiftName = detail.get("timeShiftName")+"";
            String timeShiftName = detail.get("tsName") + "";
            JSONArray sysPostNames = detail.getJSONArray("timeShiftValue");
            for (int j = 0; j < sysPostNames.size(); j++) {
                StaffAssignmentsDetailPojo staffAssignmentsDetailPojo = new StaffAssignmentsDetailPojo();
                JSONObject jsonObject1 = sysPostNames.getJSONObject(j);
                staffAssignmentsDetailPojo.setStaffAssignmentsId(staffAssignmentsId);
                staffAssignmentsDetailPojo.setTimeShiftName(timeShiftName);
                staffAssignmentsDetailPojo.setType(jsonObject1.getInteger("type"));
                staffAssignmentsDetailPojo.setCompanyId(jsonObject1.getInteger("companyId"));
                staffAssignmentsDetailPojo.setCompanyName(jsonObject1.get("companyName") + "");
                staffAssignmentsDetailPojo.setManScale(jsonObject1.getDouble("manScale"));
                staffAssignmentsDetailPojo.setWomanScale(jsonObject1.getDouble("manScale"));
                staffAssignmentsDetailPojo.setManNumber(jsonObject1.getInteger("manNumber"));
                staffAssignmentsDetailPojo.setWomanNumber(jsonObject1.getInteger("womanNumber"));
                addStaffAssignmentsDetailPojo.add(staffAssignmentsDetailPojo);
                Integer manNumber = jsonObject1.getInteger("manNumber");
                Integer womanNumber = jsonObject1.getInteger("womanNumber");
                totalManNum=totalManNum+manNumber;
                totalwoManNum=totalwoManNum+womanNumber;
                String key = timeShiftName + jsonObject1.get("companyName") + "" + "man";
                Integer integer = sumNumberMap.get(key);
                if (integer != jsonObject1.getInteger("manNumber")) {
                    TaskChangePojo taskChangePojo = new TaskChangePojo();
                    taskChangePojo.setTaskId(staffAssignmentsId);
                    taskChangePojo.setChangeUserId(user.getUserId().intValue());
                    taskChangePojo.setChangeUserName(user.getUserName());
                    taskChangePojo.setChangData(user.getUserName() + " " + timeShiftName + "-" + jsonObject1.get("companyName") + "" + "-男性，由" + integer + "改为" + jsonObject1.getInteger("manNumber"));
                    taskChangePojos.add(taskChangePojo);
                }

                key = timeShiftName + jsonObject1.get("companyName") + "woman";
                Integer integer1 = sumNumberMap.get(key);
                if (integer1 != womanNumber) {
                    TaskChangePojo taskChangePojo = new TaskChangePojo();
                    taskChangePojo.setTaskId(staffAssignmentsId);
                    taskChangePojo.setChangeUserId(user.getUserId().intValue());
                    taskChangePojo.setChangeUserName(user.getUserName());
                    taskChangePojo.setChangData(user.getUserName() + " " + timeShiftName + "-" + jsonObject1.get("companyName") + "" + "-女性，由" + integer1 + "改为" + womanNumber);
                    taskChangePojos.add(taskChangePojo);
                }
                Integer scale = jsonObject1.getInteger("manScale");
                key = timeShiftName + jsonObject1.get("companyName") + "scale";
                Integer integer2 = sumNumberMap.get(key);
                if (integer2 != scale) {
                    TaskChangePojo taskChangePojo = new TaskChangePojo();
                    taskChangePojo.setTaskId(staffAssignmentsId);
                    taskChangePojo.setChangeUserId(user.getUserId().intValue());
                    taskChangePojo.setChangeUserName(user.getUserName());
                    taskChangePojo.setChangData(user.getUserName() + " " + timeShiftName + "-" + jsonObject1.get("companyName") + "" + "-分配比例，由" + integer2 + "改为" + scale);
                    taskChangePojos.add(taskChangePojo);
                }
            }
        }

        operationNeedMapper.deleteStaffDetail(staffAssignmentsId);
        StaffAssignmentsPojo staffAssignmentsPojo =new StaffAssignmentsPojo();
        staffAssignmentsPojo.setStaffAssignmentsId(staffAssignmentsId);
        staffAssignmentsPojo.setManNumberScale(totalManNum);
        staffAssignmentsPojo.setWomanNumberScale(totalwoManNum);
        operationNeedMapper.updateStaffAssignmentsById(staffAssignmentsPojo);
        if (addStaffAssignmentsDetailPojo.size() > 0) {
            operationNeedMapper.addStaffAssignmentsDetailPojo(addStaffAssignmentsDetailPojo);
        }
        if (taskChangePojos.size() > 0) {
            for (int i = 0; i < taskChangePojos.size(); i++) {
                operationNeedMapper.addTaskChangePojo(taskChangePojos.get(i));
            }
        }
    }

    @Override
    public List<WorkerNeedPojo> getWorkerNeedList(WorkerNeedPojo workerNeedPojo) {
        List<WorkerNeedPojo> workerNeedList = operationNeedMapper.getWorkerNeedList(workerNeedPojo);
        return workerNeedList;
    }

    @Override
    public void deleteWorkerNeed(Integer workerNeedId) {
        operationNeedMapper.deleteWorkerNeed(workerNeedId);
    }

    @Override
    public void auditWorkerNeed(WorkerNeedPojo workerNeedPojo) {
        Integer workerNeedId = workerNeedPojo.getWorkerNeedId();
        WorkerNeedPojo wNeedPojo = operationNeedMapper.viewWorkerNeed(workerNeedId);
        Integer documentStatus = workerNeedPojo.getDocumentStatus();
        if (documentStatus == 2) {
            StaffAssignmentsPojo staffAssignmentsPojo = new StaffAssignmentsPojo();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String str = sdf.format(wNeedPojo.getNeedTime());
            staffAssignmentsPojo.setNeedTime(str);
            staffAssignmentsPojo.setTaskNode(0);
            staffAssignmentsPojo.setTaskNumber(wNeedPojo.getDocumentNumber());
            double lackNumber = wNeedPojo.getLackNumber();
            double manSumNumber = wNeedPojo.getLackNumberMan();
            double womanSumNumber = wNeedPojo.getLackNumberWoman();
            int manfloor =(int) Math.round(manSumNumber / lackNumber * 100);
            int womanfloor =(int) Math.round(womanSumNumber / lackNumber * 100);

            staffAssignmentsPojo.setManNumberScale(manfloor);
            staffAssignmentsPojo.setWomanNumberScale(womanfloor);
            operationNeedMapper.addStaffAssignments(staffAssignmentsPojo);
            List<Map<String, Object>> companyMapList = operationNeedMapper.getCompanyData();
            List<StaffAssignmentsDetailPojo> addStaffAssignmentsDetailPojo = new ArrayList<>();
            Map<String, StaffAssignmentsDetailPojo> maxScale = new HashMap<>();
            int realMmanNumber = 0;//实际男性用人数
            int realWomanNumber = 0;//实际女性用人数
            int maxScaleInt = 0;//最大分配比例
            Integer man = (int) manSumNumber;//当前班次实际男性用人总数
            Integer woman = (int) womanSumNumber;//当前实际女性用人总数
            for (int j = 0; j < companyMapList.size(); j++) {
                StaffAssignmentsDetailPojo staffAssignmentsDetailPojo = new StaffAssignmentsDetailPojo();
                staffAssignmentsDetailPojo.setStaffAssignmentsId(staffAssignmentsPojo.getStaffAssignmentsId());
                staffAssignmentsDetailPojo.setTimeShiftName(wNeedPojo.getTimeShift());
                staffAssignmentsDetailPojo.setType(wNeedPojo.getTimeShiftType());
                Map<String, Object> companyMap = companyMapList.get(j);
                Integer companyId = Integer.parseInt(companyMap.get("id") + "");
                String company = companyMap.get("company") + "";
                String rStr = companyMap.get("recruitPercent") + "";
                if ("".equals(rStr) || "null".equals(rStr)) {
                    rStr = "0";
                }
                double recruitPercent = Double.parseDouble(rStr);
                double manNumberfloor = Math.round(manSumNumber * recruitPercent / 100);
                double womanNumberfloor = Math.round(womanSumNumber * recruitPercent / 100);
                int manNumber = (int) manNumberfloor;
                int womanNumber = (int) womanNumberfloor;
                realMmanNumber += manNumber;
                realWomanNumber += womanNumberfloor;
                int scale = (int) recruitPercent;
                staffAssignmentsDetailPojo.setCompanyId(companyId);
                staffAssignmentsDetailPojo.setCompanyName(company);
                staffAssignmentsDetailPojo.setManScale(recruitPercent);
                staffAssignmentsDetailPojo.setWomanScale(recruitPercent);
                staffAssignmentsDetailPojo.setManNumber(manNumber);
                staffAssignmentsDetailPojo.setWomanNumber(womanNumber);
                if (scale > maxScaleInt) {//当前比例大则替换
                    maxScaleInt = scale;
                    StaffAssignmentsDetailPojo staffAssignmentsDetailPojo1 = maxScale.get("saPojo");
                    addStaffAssignmentsDetailPojo.add(staffAssignmentsDetailPojo1);
                    maxScale.put("saPojo", staffAssignmentsDetailPojo);
                } else {
                    addStaffAssignmentsDetailPojo.add(staffAssignmentsDetailPojo);
                }
            }
            if (man > realMmanNumber) {
                StaffAssignmentsDetailPojo staffAssignmentsDetailPojo = maxScale.get("saPojo");
                Integer manNumber = staffAssignmentsDetailPojo.getManNumber();
                staffAssignmentsDetailPojo.setManNumber(manNumber + (man - realMmanNumber));
            }
            if (woman > realWomanNumber) {
                StaffAssignmentsDetailPojo staffAssignmentsDetailPojo = maxScale.get("saPojo");
                Integer womanNumber = staffAssignmentsDetailPojo.getWomanNumber();
                staffAssignmentsDetailPojo.setWomanNumber(womanNumber + (woman - realWomanNumber));
            }
            addStaffAssignmentsDetailPojo.add(maxScale.get("saPojo"));
            if (addStaffAssignmentsDetailPojo.size() > 0) {
                operationNeedMapper.addStaffAssignmentsDetailPojo(addStaffAssignmentsDetailPojo);
            }
        }
        operationNeedMapper.auditWorkerNeed(workerNeedPojo);
    }

    @Override
    public JSONObject viewWorkerNeed(Integer workerNeedId) {
        JSONObject jsonObject = new JSONObject();
        WorkerNeedPojo workerNeedPojo = operationNeedMapper.viewWorkerNeed(workerNeedId);
        jsonObject.put("workerNeedPojo", workerNeedPojo);
        jsonObject.put("checkData", "");
        return jsonObject;
    }

    @Override
    public void auditQualityPredict(QualityPredictPojo qualityPredictPojo) {
        operationNeedMapper.auditQualityPredict(qualityPredictPojo);
    }

    @Override
    public void deleteQualityPredict(Integer qualityPredictId) {
        operationNeedMapper.deleteQualityPredict(qualityPredictId);
    }

    @Override
    public void updateQualityPredict(JSONObject jsonObject) {
        JSONObject jsonObj = jsonObject.getJSONObject("qualityPredictPojo");
        QualityPredictPojo qualityPredictPojo = new QualityPredictPojo();
        qualityPredictPojo.setQualityPredictId(jsonObj.getInteger("qualityPredictId"));
        qualityPredictPojo.setFuture24PredictNumber(jsonObj.getDouble("future24PredictNumber"));
        qualityPredictPojo.setFuture12PredictNumber(jsonObj.getDouble("future12PredictNumber"));
        qualityPredictPojo.setPredictNumber(jsonObj.getDouble("predictNumber"));
        qualityPredictPojo.setCarNumber(jsonObj.getInteger("carNumber"));
        qualityPredictPojo.setProvinceNotIssued(jsonObj.getDouble("provinceNotIssued"));
        qualityPredictPojo.setUnloadedNumber(jsonObj.getDouble("unloadedNumber"));
        operationNeedMapper.updateQualityPredict(qualityPredictPojo);
    }

    @Override
    public int addQualityPredict(JSONObject jsonObject) {
        JSONObject qualityPredictPojo1 = jsonObject.getJSONObject("qualityPredictPojo");
        JSONArray aConst = jsonObject.getJSONArray("const");
        QualityPredictPojo qualityPredictPojo = JSON.toJavaObject(qualityPredictPojo1, QualityPredictPojo.class);
        operationNeedMapper.addQualityPredict(qualityPredictPojo);
        if (aConst != null) {
            List<QualityPredictUploadPojo> list = new ArrayList<>();
            for (int i = 0; i < aConst.size(); i++) {
                QualityPredictUploadPojo qualityPredictUploadPojo = new QualityPredictUploadPojo();
                qualityPredictUploadPojo.setQualityPredictId(qualityPredictPojo.getQualityPredictId());
                qualityPredictUploadPojo.setFileName(aConst.get(i) + "");
                list.add(qualityPredictUploadPojo);
            }
            if (list.size() > 0) {
                operationNeedMapper.addQualityPredictUploadList(list);
            }
        }
        return 0;
    }

    @Override
    public void updateWorkerNeed(JSONObject jsonObject) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        WorkerNeedPojo workerNeedPojo = JSON.toJavaObject(jsonObject, WorkerNeedPojo.class);
        workerNeedPojo.setUpdateUserName(user.getUserName());
        operationNeedMapper.updateWorkerNeed(workerNeedPojo);
    }
}
